<template>
<!--  <div style="position: fixed; z-index: -1; width: 100%; height: 100%">-->
<!--    <video autoplay loop muted style="width: 100%; height: 100%; object-fit: cover;">-->
<!--      <source src="../assets/mp4/rePassword.mp4" type="video/mp4">-->
<!--    </video>-->
<!--  </div>-->
  <div class="loginPage">
    <div class="container">
      <!-- 图片 -->
      <div class="image-container">
        <img class="img" src="../assets/img/undraw_Forgot_password_re_hxwm.png" alt="">
      </div>
      <!-- 表单 -->
      <div class="form-container">
        <!--   添加一个 @keyup.enter 事件监听器,按下回车键触发重设密码事件     -->
        <el-form :model="data.user" class="form" :rules="data.rules" ref="ruleFormRef" @keyup.enter="rePassword">
          <div class="loginTitle">通过邮箱找回账户密码</div>

          <el-form-item prop="email">
            <el-input size="large" :prefix-icon="Message" placeholder="请输入邮箱账号" v-model="data.user.email"></el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input size="large" :prefix-icon="Lock" show-password placeholder="请输入密码"
                      v-model="data.user.password"></el-input>
          </el-form-item>

          <el-form-item prop="ConfirmPassword">
            <el-input size="large" :prefix-icon="Lock" show-password placeholder="请再次输入密码"
                      v-model="data.user.ConfirmPassword"></el-input>
          </el-form-item>

          <el-form-item prop="InputValidCode">
            <el-input class="validCode-input" size="large" :prefix-icon="CircleCheck" placeholder="请输入验证码"
                      v-model="data.user.InputValidCode"></el-input>
            <div class="validCode">
              <el-button
                  :disabled="!data.user.email || !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(data.user.email)"
                  v-if="data.showSendButton" @click="sendCode" :loading="data.loading">点击获取验证码
              </el-button>
              <div v-else>{{ data.Countdown }}秒后可重新获取</div>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary"
                       :disabled="!data.user.email || !data.user.password || !data.user.ConfirmPassword || !data.user.InputValidCode"
                       style="width: 100%;" @click="rePassword">确 定
            </el-button>
          </el-form-item>
          <div style="display: flex;justify-content: space-around">
            <span class="register-link" @click="$router.push('/login')">>>返回登录</span>
<!--            <span class="register-link" @click="$router.push('/register')">注册</span>-->
          </div>
        </el-form>
      </div>
    </div>
  </div>
  <el-footer class="footer">
    <div class="footer-content">
      <span>©2024 ldystudy.cn 版权所有</span>
      <a target="_blank" class="a-left"
         href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=52262202000037">
        <img src="/备案图标.png" style="float:left;height: 50%;"/>
        <p>
          贵公网安备 52262202000037号
        </p>
      </a>
      <a class="a-right" href="https://beian.miit.gov.cn" target="_blank">工信部备案：黔ICP备2023009910号</a>
    </div>
  </el-footer>
</template>

<script setup>
import {reactive, ref} from 'vue';
import {CircleCheck, Lock, Message} from '@element-plus/icons-vue';
import {useRouter} from "vue-router";
import request from "@/utils/request.js";
import {ElLoading, ElMessage} from "element-plus";

const ruleFormRef = ref(null);

// 定义一个自定义验证器来检查确认密码是否与密码匹配
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== data.user.password) {
    callback(new Error("两次密码输入不一致"));
  } else {
    callback();
  }
};


const data = reactive({
  loading:null,
  showSendButton: true,
  Countdown: 60,
  user: {
    email: 'ldyyyazmm.1314@gmail.com',
    // email: '1738464117@qq.com',
    // email: '2822846684@qq.com',
    password: 'Ldy12345678',
    ConfirmPassword: 'Ldy12345678',
    InputValidCode: '', // 用户输入的验证码
  },
  rules: {
    email: [
      {required: true, message: "请输入邮箱账号", trigger: "blur"},
      {type: 'email', message: "请输入正确的邮箱地址", trigger: ['blur', 'change']}
    ],
    password: [
      {required: true, message: "请输入密码", trigger: "blur"},
      {min: 8, max: 20, message: "密码长度为[8-20]", trigger: "blur"},
      {pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,20}$/, message: "密码必须同时含有大小写字母和数字", trigger: "blur"}
    ],
    ConfirmPassword: [
      {required: true, message: "请输入确认的密码", trigger: "blur"},
      {min: 8, max: 20, message: "密码长度为[8-20]", trigger: "blur"},
      // 这里需要一个验证器来确认两次密码是否相同
      {validator: validateConfirmPassword, trigger: "blur"} // 自定义验证器
    ],
    InputValidCode: [ // 验证码的校验规则
      {required: true, message: "请输入验证码", trigger: "blur"},
    ],
  },
});


// 点击登录按钮进行表单验证和登录
const router = useRouter();

const rePassword = () => {
  const rePasswordData = {
    email: data.user.email,
    password: data.user.password,
    code: data.user.InputValidCode,
  }
  request.put(`/user/rePassword`, rePasswordData).then((res) => {
    console.log("确认修改密码:", res)
    if (res.code === 200) {
      ElMessage.info(res.data)
    } else {
      ElMessage.error(res.msg)
    }
  })
}


// 设置loading状态
const setLoading = (value) => {
  data.loading = value;
};

const sendCode = () => {
  setLoading(true); // 按钮显示加载状态
  request.get(`/user/getCountdown/${data.user.email}`).then((res) => {
    console.log("获取倒计时:", res)
    setLoading(false); // 关闭按钮加载状态
    if (res.data !== "-2") {
      data.showSendButton = false
      data.Countdown = res.data
      // 假设点击发送后，开始60秒倒计时
      let countdownInterval = setInterval(() => {
        if (data.Countdown > 0) {
          data.Countdown--;
        } else {
          clearInterval(countdownInterval);
          data.showSendButton = true;
        }
      }, 1000);
    } else {
      //Loading加载
      let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
      request.get(`/user/email/${data.user.email}`).then((res) => {
        if (res.data === "success") {
          ElMessage.info("验证码已发送至邮箱，请注意查收")
          data.showSendButton = false
          request.get(`/user/getCountdown/${data.user.email}`).then((res) => {
            data.Countdown = res.data
            // 假设点击发送后，开始60秒倒计时
            let countdownInterval = setInterval(() => {
              if (data.Countdown > 0) {
                data.Countdown--;
              } else {
                clearInterval(countdownInterval);
                data.showSendButton = true;
              }
            }, 1000);
          })
        }
      }).finally(() => {
        loadingInstance.close(); // 无论请求成功或失败，都关闭加载动画
      });
    }
  })
}


</script>

<style scoped>
.footer {
  background-color: white;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.footer-content {
  height: 100%;
  margin-left: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.a-left {
  display: flex;
  align-items: center;
  margin-left: 2%;
  text-decoration: none;
  color: black
}

.a-right {
  margin-left: 2%;
  text-decoration: none;
  color: black
}

.a-right:hover,
.a-left:hover {
  color: blue;
}
</style>

<style scoped>
.loginPage {
  display: flex;
  height: 100vh;
  align-items: center;
  justify-content: center;
  /*background-color: #001529;*/
  /*background-image: url("../assets/img/back.jpg");*/
  /*background-repeat: no-repeat; !* 背景图片不重复 *!*/
  /*background-size: 100%;*/
}

.container {
  display: flex;
  width: 50%;
  height: 60vh;
  border-radius: 5px;
  background-color: white;
  overflow: hidden;
}

.loginTitle {
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 50px;
}

.image-container,
.form-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form {
  width: 80%;
}

.validCode-input {
  flex: 1;
}

.validCode {
  flex: 1;
  display: flex;
  justify-content: center;
  cursor: pointer;
  color: #a8abb2;
}



.register-link {
  color: #409eff;
  cursor: pointer;
  width: 90%;
}


.loginTitle,
.img,
.login-button {
  width: 100%;
}
</style>